//
//  NSMutableArray+Safe.m
//  TestMethod
//
//  Created by js on 15/11/9.
//  Copyright © 2015年 js. All rights reserved.
//

#import "NSMutableArray+LBSafe.h"
#import <objc/runtime.h>

@implementation NSMutableArray (LBSafe)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        //NSMutableArray
        Method mmethod = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(objectAtIndex:));
        Method mmethod2 = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(safeObjectAtIndex:));
        method_exchangeImplementations(mmethod, mmethod2);
        
        Method methodAdd = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(addObject:));
        Method method2Add = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(safeAddObject:));
        method_exchangeImplementations(methodAdd, method2Add);
    });
}


- (id)safeObjectAtIndex:(NSInteger)index {
    @autoreleasepool {
        if (index < self.count) {
            return [self safeObjectAtIndex:index];
        }
        
        NSLog(@"数组越界");
        return nil;
    }
}

- (void)safeAddObject:(id)obj{
    
    @autoreleasepool {
        if (obj) {
            [self safeAddObject:obj];
        }
        else{
            NSLog(@"数组添加空对象");
        }
    }
}

@end
